
package com.zkmonitor.controller;

import com.zkmonitor.common.UserHolder;
import com.zkmonitor.util.ZkMonitorConstants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/")
public class IndexController {

    @Value("${cas.logout.url}")
    private String casServerLogoutUrl;

    @Value("${server.url}")
    private String serverUrl;

    @Value("${server.login.type}")
    private String loginType;

    @Autowired
    private UserHolder userHolder;

    /**
     * Logouts.
     *
     * @param request
     * @return
     */
    @RequestMapping("logout")
    public String logout(HttpServletRequest request) {
        request.getSession().invalidate();
        String referer = request.getHeader(HttpHeaders.REFERER);
        if (StringUtils.isBlank(referer)) {
            referer = serverUrl;
        }
        if (ZkMonitorConstants.LOGIN_TYPE_CAS.equals(loginType.toUpperCase())) {
            return "redirect:" + casServerLogoutUrl + "?service=" + referer;
        }
        return "redirect:" + referer;
    }

    /**
     * Login.
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String login(HttpServletRequest request) {
        if (userHolder == null || userHolder.getUser() == null) {
            return "login";
        } else {
            return "redirect:/";
        }
    }
}
